/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  TouchableOpacity,
  Dimensions,
  ScrollView,
  Platform,
  BackHandler,
  NativeModules,
  AsyncStorage,
  DeviceEventEmitter,
  TouchableHighlight,
  Keyboard,
  StatusBar,
  
} from 'react-native';

import Toast from 'react-native-root-toast';

import ToolbarComponent from '../../component/ToolbarComponent';

import Common from '../../component/common';
import AppStorage from '../../component/appstorage';
import Index from './index';

const os = Platform.OS;

const totalWidth = Dimensions.get('window').width;

const totalHeight = Dimensions.get('window').height;

const JsAndroid = NativeModules.JsAndroid;

const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 20;

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: '',
      isSend: false,
      times: 60,
      disabled:false,
      isShowLogol: true,
      qq: true,
      wechat: true,
      weibo: true,
    };
    this.timer = null;
  }

  componentWillMount(){
    if( os === 'ios'){
      JsAndroid.checkThirdStatus((e) => {
        this.setState({
          wechat: e.wechat,
          qq: e.qq,
          weibo: e.weibo,
        })
      });
    }
	  var that = this;
    if (os == 'android') {
      BackHandler.addEventListener('hardwareBackPress', () => Common.onBack(this));
    }
  	this.listener=DeviceEventEmitter.addListener('thirdLogin', (e)=>{
  		Common.onBack(that);
  		this.getThirdLoginInfo();
      DeviceEventEmitter.emit('loginStatus',null);
  	});
    // this.keyboardDidShowListener = Keyboard.addListener('keyboardDidChangeFrame', this._keyboardDidShow);
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    
  }
  componentWillUnmount() {
  	this.timer && clearInterval(this.timer);
    if (os == 'android') {
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));
    }
    this.listener.remove();
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
    
  }
  _keyboardDidShow = (e) => {
      this.setState({
          isShowLogol: false,
      });
      // alert("keyboardDidChangeFrame");

  }

  _keyboardDidHide = (e) => {
      this.setState({
        isShowLogol: true,
      })
  }
  async getThirdLoginInfo(){
		try {
			var content = await NativeModules.JsAndroid.jsGetLoginUserInfo();
			AppStorage._updataLocalData("login", content);
			DeviceEventEmitter.emit('saveUserInfo',content);
      loginInfo = content;
		} catch (e) {
			console.log(e);
		}
	};
  
  login = () => {
    console.log(this.refs.phone._lastNativeText);
    console.log(this.refs.code._lastNativeText);
    // var reg = /^[0-9]{4}$/;
    let regExt = /^(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
    var mobile = this.refs.phone._lastNativeText;
    var smsValidateCode = this.refs.code._lastNativeText;

    // if((mobile && regExt.test(mobile)) && (smsValidateCode && reg.test(smsValidateCode))){
    if((mobile && regExt.test(mobile)) && smsValidateCode){
      let formData = new FormData();
      formData.append("mobile",mobile);
      formData.append("smsValidateCode",smsValidateCode);
      Common.fetchData("post", "/user/login", formData, (responseData) => {
        AppStorage._updataLocalData("login",responseData.entity);
        DeviceEventEmitter.emit('saveUserInfo',responseData.entity);
        DeviceEventEmitter.emit('loginStatus',null);
        loginInfo = responseData.entity;
        Common.onBack(this);
      },() => {
      	this.setState({
    		mesError:true,
    		mesErrorText:'手机号或验证码输入有误',
    	})
      },() => {
        Toast.show("请求发送失败！", {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                    shadow: true,
                    animation: true,
                    hideOnPress: true,
                    delay: 0});
        });
    }else{
      if(!mobile){
      	this.setState({
    		phoneError:true,
    		phoneErrorText:'手机号不能为空',
    	})
      }
      if(!smsValidateCode){
      	this.setState({
    		mesError:true,
    		mesErrorText:'验证码不能为空',
    	})
      }
      if(mobile && !regExt.test(mobile)){
      	this.setState({
    		phoneError:true,
    		phoneErrorText:'请输入正确的手机号',
    	})
      }
     //  if(smsValidateCode && !reg.test(smsValidateCode)){
     //  	this.setState({
    	// 	mesError:true,
    	// 	mesErrorText:'验证码输入有误',
    	// })
     //  }
    }
  };
  sendCode = () => {
    console.log(this.refs.phone._lastNativeText);
    var mobile = this.refs.phone._lastNativeText;
    // /user/sendSms
    let regExt = /^(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
    if(mobile && regExt.test(mobile)){
    	this.setState({
	    	isSend: true,
	    	disabled:true,
	    });
	    var aa = 60;
	    this.timer = setInterval(() => {
	     aa=aa-1;
	     this.setState({times: aa});
			if(this.state.times<=0){
			   	clearInterval(this.timer);
				this.setState({
					isSend: false,
					disabled:false,
					times:60,
				});
			}
		},1000);
		this.setState({
    		phoneError:false,
    		phoneErrorText:'',
    	})
      let formData = new FormData();
      formData.append("mobile",mobile);
      Common.fetchData("post", "/user/sendSms", formData, (responseData) => {
        console.log(responseData);

      },() => {
        Toast.show("验证码获取失败！", {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                    shadow: true,
                    animation: true,
                    hideOnPress: true,
                    delay: 0});
      },() => {
        Toast.show("请求发送失败！", {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                    shadow: true,
                    animation: true,
                    hideOnPress: true,
                    delay: 0});
      });
    }else{
    	if(!mobile){
			this.setState({
				phoneError:true,
				phoneErrorText:'手机号不能为空',
			})
			return;
		}
	    if(!regExt.test(mobile)){
			this.setState({
				phoneError:true,
				phoneErrorText:'请输入正确的手机号',
			})
		}
    }
  };
  
  render() {
    var again = this.state.isSend ? this.state.times+"s" : "发送验证码";
    // var wechat = true, qq = true, weibo = true;
    
    return (
      <View style={styles.container}>
        {/*标题行*/}
        <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT}>登录</Text>
          </View>
        </ToolbarComponent>
        <ScrollView keyboardShouldPersistTaps='handled'>
          <View style={styles.content}>
          {
            this.state.isShowLogol?<Image style={styles.icon} source={require('../../images/mine/yingxiang.png')}/>:null
          }
            <View style={[styles.loginInputBox,{marginTop: totalWidth*0.133}]}>
              <Image style={styles.inputIcon} source={require('../../images/mine/telephone.png')} />
              <TextInput 
	              	ref="phone" 
	              	style={styles.loginInput} 
	              	maxLength={11} 
	              	dataDetectorTypes="phoneNumber" 
	              	keyboardType="numeric"
	              	underlineColorAndroid="transparent" 
	              	placeholder="请输入手机号" 
                  onSubmitEditing={this.login} 
	              	onChange={(value)=>{
	              		if(this.state.phoneError){
	              			this.setState({
				    			phoneError:false,
				    			phoneErrorText:'',
				    		})
	              		}
	              	}}
	              	onBlur={()=>{
	              		let regExt = /^(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/;
	              		let mobile = this.refs.phone._lastNativeText;
	              		if(!mobile){
				    		this.setState({
				    			phoneError:true,
				    			phoneErrorText:'手机号不能为空',
				    		})
				    		return;
				    	}
	              		if(!regExt.test(mobile)){
				    		this.setState({
				    			phoneError:true,
				    			phoneErrorText:'请输入正确的手机号',
				    		})
				    	}
	              		
	              	}}
              />
              <TouchableOpacity onPress={() => {
              	this.refs.phone.clear();
              	this.setState({
				    	phoneError:true,
				    	phoneErrorText:'手机号不能为空',
				})
              }}>
                <Image style={{width: totalWidth*0.05,height: totalWidth*0.05,resizeMode: 'contain'}} source={require('../../images/mine/delete.png')} />
              </TouchableOpacity>
            </View>
            <View style={{width: totalWidth*0.9,height: totalWidth*0.092,justifyContent:"center",paddingHorizontal:totalWidth*0.064}}>
	            {
	            	this.state.phoneError ? 
	            	<Text style={{textAlign:'left',color:"#ff5a5a"}}>
	            		{this.state.phoneErrorText}
	            	</Text>:null
	            }
            </View>
            <View style={styles.loginInputBox}>
              <Image style={styles.inputIcon} source={require('../../images/mine/password.png')} />
              <TextInput 
	              	ref="code" 
	              	style={[styles.loginInput,styles.codeInput]} 
	              	keyboardType="numeric"
	              	underlineColorAndroid="transparent" 
	              	placeholder="请输入验证码"
                  onSubmitEditing={this.login}
	              	onChange={(value)=>{
	              		if(this.state.mesError){
	              			this.setState({
				    			mesError:false,
				    			mesErrorText:'',
				    		})
	              		}
	              	}}
	              	onBlur = {(value)=>{
	              		// var reg = /^[0-9]{4}$/;
                    let mess=this.refs.code._lastNativeText;
                    if(!mess){
                      this.setState({
                        mesError:true,
                        mesErrorText:'验证码不能为空',
                      })
                      return;
                    }
	              	// 	if(!reg.test(mess)){
	              	// 		this.setState({
      				    		// 	mesError:true,
      				    		// 	mesErrorText:'验证码输入有误',
      				    		// })
	              	// 	}
	              	}}
              />
              <View style={styles.line}/>
              <TouchableOpacity onPress={this.sendCode} disabled = {this.state.disabled}>
                <Text style={styles.codeSend}>{again}</Text>
              </TouchableOpacity>
            </View>
            <View style={{width: totalWidth*0.9,height: totalWidth*0.092,justifyContent:"center",paddingHorizontal:totalWidth*0.064}}>
	            {
	            	this.state.mesError ? 
	            	<Text style={{textAlign:'left',color:"#ff5a5a"}}>
	            		{this.state.mesErrorText}
	            	</Text>:null
	            }
            </View>
            <TouchableOpacity style={styles.loginButton} onPress={this.login}>
              <Text style={styles.loginButtonL}>登   录</Text>
            </TouchableOpacity>
            {
              this.state.wechat || this.state.qq || this.state.weibo?
            <View style={styles.loginOther}>
              <View style={styles.loginOtherTB}>
                <View style={styles.loginOtherLine}/>
                <Text style={styles.loginOtherLabel}>其他登录方式</Text>
              </View>
              <View style={styles.loginMethod}>
               {this.state.wechat?
                <TouchableHighlight underlayColor="transparent" activeOpacity={0.5} delayPressIn={100} onPress={() => JsAndroid.jsOpenThirdPartyLoginActivity("weixin")}>
                  <View style={styles.loginItem}>
                    <Image style={styles.loginIcon} source={require('../../images/mine/Wechat.png')} />
                    <Text style={styles.loginLabel}>微信登录</Text>
                  </View>
                </TouchableHighlight>:null
                }
                {this.state.qq?
                <TouchableHighlight underlayColor="transparent"  activeOpacity={0.5} delayPressIn={100} onPress={() => JsAndroid.jsOpenThirdPartyLoginActivity("qq")}>
                  <View style={styles.loginItem}>
                    <Image style={styles.loginIcon} source={require('../../images/mine/QQ.png')} />
                    <Text style={styles.loginLabel}>QQ登录</Text>
                  </View>
                </TouchableHighlight>:null
                }
                {/*this.state.weibo?
                <TouchableHighlight underlayColor="transparent" activeOpacity={0.5} delayPressIn={100} onPress={() => JsAndroid.jsOpenThirdPartyLoginActivity("weibo")}>
                  <View style={styles.loginItem}>
                    <Image style={styles.loginIcon} source={require('../../images/mine/Weibo.png')} />
                    <Text style={styles.loginLabel}>微博登录</Text>
                  </View>
                </TouchableHighlight>:null
                */}
              </View>
            </View>:null
            }
          </View>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f6f6f6',
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  content: {
    flex: 1,
    height: totalHeight-totalWidth*0.112-STATUS_BAR_HEIGHT,
    alignItems: 'center'
  },
  inputIcon: {width: totalWidth*0.037,height: totalWidth*0.045,resizeMode: 'contain'},
  icon: {
    marginTop: totalWidth*0.133,
  },
  loginInputBox: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: totalWidth*0.9,
    height: totalWidth*0.11,
    paddingHorizontal: totalWidth*0.064,
    borderWidth: 1,
    borderColor: '#dcdfe4',
    borderRadius: totalWidth*0.05,
    backgroundColor: '#fff',
  },
  loginInput: {
    width: totalWidth*0.613,
  },
  line: {
    height: totalWidth*0.1,
    borderColor:"#dadfe3",
    borderRightWidth: 1
  },
  codeInput: {
    width: totalWidth*0.45,
  },
  codeSend: {
    color: '#ff5c5d'
  },
  message: {
    color: "#ff5c5d",
    alignSelf: "flex-start",
    marginLeft: totalWidth*0.11,
  },
  loginButton: {
    width: totalWidth*0.833,
    height: totalWidth*0.11,
    backgroundColor: '#ff5b5a',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: totalWidth*0.1,
    marginTop: totalHeight*0.025,
  },
  loginButtonL: {
    color: '#fff',
    fontSize: 20,
  },
  loginOther: {
    position: 'absolute',
    bottom: 0,
    width: totalWidth,
  },
  loginOtherTB: {

  },
  loginOtherLine: {
    borderTopWidth: 1,
    borderColor: '#ecf0f3',
  },
  loginOtherLabel: {
    width: totalWidth*0.5,
    height: totalWidth*0.05,
    textAlign: 'center',
    position: 'absolute',
    top: -totalWidth*0.025,
    left: totalWidth*0.25,
    color: '#bfbfbf',
    backgroundColor: '#f6f6f6'
  },
  loginMethod: {
    flexDirection: 'row',
    marginVertical: totalWidth*0.08,
    justifyContent: 'space-around',
  },
  loginItem: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  loginIcon: {
    width: totalWidth*0.128,
    height: totalWidth*0.128,
    resizeMode: 'contain',
  },
  loginLabel: {
    marginTop: totalWidth*0.03,
    color: '#3a3a3a'
  }
});